package com.qf.admin.shiro;

import com.qf.common.http.ResultCode;
import com.qf.entiy.dto.Admin;
import com.qf.entiy.po.LoginAdmin;
import com.qf.service.impl.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;
//自定义realm
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private AdminService adminService;

    //权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Set<String> permissionSet = new HashSet<>();
        permissionSet.add("ADMINISTRATOR");
        simpleAuthorizationInfo.setStringPermissions(permissionSet);
        return simpleAuthorizationInfo;
    }
    //验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());
        Admin admin = adminService.getByUserName(username);
        if (admin == null){
            throw new RuntimeException(ResultCode.LOGIN_ERROR.getDescription());
        }
        if (!admin.getPassword().equals(password)){
            throw new RuntimeException(ResultCode.LOGIN_ERROR.getDescription());
        }
        LoginAdmin loginAdmin = new LoginAdmin();
        loginAdmin.setId(admin.getId());
        loginAdmin.setName(admin.getName());
        loginAdmin.setRoleId(admin.getRoleId());
        loginAdmin.setDescription(admin.getDescription());
        return new SimpleAuthenticationInfo(loginAdmin,admin.getPassword(),admin.getAccount());
    }
}
